﻿using Microsoft.AspNetCore.Components;
using System;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Components.Web.Security;

namespace Allin.Abp.AspNetCore.Components.Web.AntDesignTheme.Themes.AntDesign.Navigation
{
    public partial class MainMenu
    {
        [Parameter]
        public bool Collapsed { get; set; }

        [Inject] protected MainMenuProvider MainMenuProvider { get; set; }

        [Inject] protected ApplicationConfigurationChangedService ApplicationConfigurationChangedService { get; set; }

        [Parameter] public EventCallback OnClickCallback { get; set; }

        protected MenuViewModel Menu { get; set; }

        protected override async Task OnInitializedAsync()
        {
            Menu = await MainMenuProvider.GetMenuAsync();
            Menu.StateChanged += Menu_StateChanged;
            ApplicationConfigurationChangedService.Changed += ApplicationConfigurationChanged;
        }

        private void Menu_StateChanged(object sender, EventArgs e)
        {
            InvokeAsync(StateHasChanged);
        }

        private async void ApplicationConfigurationChanged()
        {
            Menu.StateChanged -= Menu_StateChanged;
            Menu = await MainMenuProvider.GetMenuAsync();
            Menu.StateChanged += Menu_StateChanged;
            await InvokeAsync(StateHasChanged);
        }

        public void Dispose()
        {
            Menu.StateChanged -= Menu_StateChanged;
            ApplicationConfigurationChangedService.Changed -= ApplicationConfigurationChanged;
        }
    }
}
